import { s_getSelectData, s_getStockInfo, s_operateInfo, s_stockIn, status2text } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { Button ,Col,Divider,Image, message, Modal, Row, Space, Tag} from "antd";
import moment from "moment";
import { useRef, useState } from "react";
import { useModel } from "@umijs/max";

const App:React.FC=()=>{
    const [tdata,setTdata]=useState<any[]>([]);
    const [selectedRecords,setSelectedRecords]=useState<any[]>([]);
    const { initialState, setInitialState } = useModel('@@initialState');

    const actionRef_m=useRef<ActionType>();
    //新增
    const [etype,setEtype]=useState(1);
    const [open,setOpen]=useState(false);
    const formRef_main=useRef<ProFormInstance>();
    const editableRef_main=useRef<EditableFormInstance>();
    const actionRef_main=useRef<ActionType>();

    //查询
    const [openQuery,setOpenQuery]=useState(false);
    const [selectedRecords3,setSelectedRecords3]=useState<any[]>([]);
    const [tdata3,setTdata3]=useState<any[]>([]);
    const formRef_query=useRef<ProFormInstance>();
    const editableRef_query=useRef<EditableFormInstance>();
    const actionRef_query=useRef<ActionType>();
    const [total,setTotal]=useState(50);

    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

    interface DataType{
//         x_id,id,vouch_code,org_id,warehouse_id,intype_id,worker_id,memo,
// operater_id,isreplace,operate_time,repworker_id,workcenter_id,workgroup_id,stockin_time,
// warehouse_name,intype_name,worker_name,workcenter_name,workgroup_name,status
x_id?:number,id?:number,vouch_code?:string,org_id?:number,warehouse_id?:number,intype_id?:number,
worker_id?:number,memo?:string,
operater_id?:number,isreplace?:number,operate_time?:string,repworker_id?:number,workcenter_id?:number,
workgroup_id?:number,stockin_time?:string,
warehouse_name?:string,intype_name?:string,worker_name?:string,workcenter_name?:string,
workgroup_name?:string,status?:number
        
    };

    const columns:ProColumns<DataType>[]=[
        {dataIndex:'warehouse_name',title:'仓库',search:false}, 
        {dataIndex:'stockin_time',title:'入库时间',valueType:'date',width:200},
        {dataIndex:'vouch_code',title:'入库单号'},
        {dataIndex:'source_type',title:'类型',search:false,
            render:(text)=>text==1?<Tag style={{width:80}}>备料入库</Tag>
                 :text==3?<Tag style={{width:80}}>外发入库</Tag>:<Tag >无</Tag>,
        },
        // {dataIndex:'worker_name',title:'操作工' },
        // {dataIndex:'intype_id',title:'SS'},
       
        {dataIndex:'intype_name',title:'入库类别',search:false,},
        {dataIndex:'workcenter_name',title:'外发中心',width:200},{dataIndex:'workgroup_name',title:'外发商',width:200}, 
        {dataIndex:'memo',title:'备注',search:false},

        {dataIndex:'status',title:'状态',valueType:'select',width:100,
            valueEnum:{1:{text:'未审核'},5:{text:'已审核'},
            6:{text:'已弃审'},2:{text:'关闭'},3:{text:'删除'},9:{text:'全部'}}
        }, 
        
    ];

    interface DataType2{
        // id,mid,source_produce_order_did,source_taskcard_id,material_id,quantity,userdefine_id,userdefine_name,operate_time,memo,
        // code,name,invstd,invstd2,pic,munit_name,card_name,taskcard_sno
        id?:number,mid?:number,source_produce_order_did?:number,source_taskcard_id?:number,material_id?:number,
        quantity?:number,userdefine_id?:string,userdefine_name?:string,operate_time?:string,memo?:string,
        code?:string,name?:string,invstd?:string,invstd2?:string,pic?:string,
        munit_name?:string,card_name?:string,taskcard_sno?:string
    };

    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'pic',title:'图片' ,editable:false,
        //     render:(text)=>{
        //         var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
        //         return <Image src={pic}  
        //                style={{width:100,height:100}} alt='无' />
        //    },
        //  },
          render:(text,record,index,k)=>{
                               var pic="/basis_api/file/get2?filename="+record.code;
                               return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
                  } 
         },
         {dataIndex:'mid',title:'mid',hidden:true},{dataIndex:'id',title:'ID',hidden:true},
        {dataIndex:'code',title:'SKU'},{dataIndex:'name',title:'名称'},
        {dataIndex:'invstd',title:'包装规格'},
        {dataIndex:'invstd2',title:'型号'}, 
        {dataIndex:'munit_name',title:'单位'},
        {dataIndex:'quantity',title:'入库数量',
            render:(text:any)=>text>=0?<Tag style={{width:80}}>{text}</Tag>:<Tag color="red" style={{width:80}}>{text}</Tag>,
        }, 
        {dataIndex:'memo',title:'备注'}, 
        {dataIndex:'card_name',title:'工序名'},{dataIndex:'taskcard_sno',title:'工序任务号'},
        {
            title:'操作',            
            fixed:'right',
            valueType:'option',
            width:80,
            editable:false,
            render:(text,record,_,action)=>[
               <a  key='del2'
                   onClick={()=>{
                     var x:any[]=editableRef_main.current?.getRowsData?.();
                     formRef_main.current?.setFieldValue('editable_main',x.filter((item)=>item.rid!=record.rid));
                   }}
               >
                   删除
               </a>,
            ]
         }
    ];

    //从采购订单生单的界面数据
    interface DataType3{
//         rid,id,x_id,vouch_code,vendor_id,status,memo,operate_time,
//  did,material_id,userdefine_id,userdefine_name,quantity,deliverdate,source_type,source_mid,source_did,
//  quantity_deliver,quantity_reback,quantity_stockin,quantity_undeliver,
//  code,name,invstd,invstd2,munit_name,pic,
//  vendor_name,quantity_in_now
rid?:number,id?:number,x_id?:number,vouch_code?:string,vendor_id?:number,status?:number,memo?:string,
operate_time?:string,
 did?:number,material_id?:number,userdefine_id?:string,userdefine_name?:string,quantity?:number,
 deliverdate?:string,source_type?:string,source_mid?:number,source_did?:number,
 quantity_deliver?:number,quantity_reback?:number,quantity_stockin?:number,quantity_undeliver?:number,
 code?:string,name?:string,invstd?:string,invstd2?:string,munit_name?:string,pic?:string,
 vendor_name?:string,quantity_in_now?:number
    };

    const columns3:ProColumns<DataType3>[]=[
        {dataIndex:'pic',title:'图片' ,editable:false,
        //     render:(text)=>{
        //         var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
        //         return <Image src={pic}  
        //                style={{width:100,height:100}} alt='无' />
        //    },
        //  },
        render:(text,record,index,k)=>{
                               var pic="/basis_api/file/get2?filename="+record.code;
                               return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
                  } 
                },
       {dataIndex:'rid',title:'rid',editable:false},{dataIndex:'did',title:'did',editable:false},
       {dataIndex:'vendor_id',title:'供应商ID',editable:false,},{dataIndex:'vendor_name',title:'供应商',editable:false},
       {dataIndex:'vouch_code',title:'采购单号',editable:false},{dataIndex:'material_id',title:'商品ID',editable:false},
       {dataIndex:'code',title:'SKU',editable:false},{dataIndex:'name',title:'名称',editable:false},
       {dataIndex:'invstd',title:'包装规格',editable:false},{dataIndex:'invstd2',title:'型号',editable:false},
       {dataIndex:'munit_name',title:'单位',editable:false},
       {dataIndex:'quantity',title:'总数量',editable:false},
       {dataIndex:'deliverdate',title:'预计交货日期',editable:false,valueType:'date'},
       {dataIndex:'quantity_deliver',title:'已交货数',editable:false},{dataIndex:'quantity_reback',title:'退货数',editable:false},
       {dataIndex:'quantity_undeliver',title:'未交货数',editable:false}, 
       {dataIndex:'quantity_in_now',title:'本次入库数',width:120,valueType:'digit' },
       {dataIndex:'operate_time',title:'下单日期',editable:false,valueType:'date'},
    //    {dataIndex:'status',title:'状态',editable:false},
    ];

     //  操作询价单/冻结/删除/恢复
           async function operateInfo(n:number){
            // source,x_id,operater_id,otype,id
            if(selectedRecords.length==0)
               message.warning('请选择要操作的行');
           else if(n==5&&selectedRecords[0].status==5)
                        message.warning('此单据已审核，请不要重复操作');
             else if(n==6&&selectedRecords[0].status!=5)
                        message.warning('此单据未审核，不能弃审');        
            else{
             const x=await s_operateInfo({x_id:1,source:'stock_in_produce_main',operater_id:initialState?.currentUser?.userid,
                         otype:n,id:selectedRecords[0].id});
             if(x.success){
               message.success('操作成功');
               actionRef_m.current?.reloadAndRest?.();
             }else
               message.error('操作错误，请联系管理员。');
            }
         }

    // 打开入库单编辑窗口---1新增，0编辑
    function openMain(type:number){
       setEtype(type);
       setOpen(true);
    };

    //退出入库单编辑窗口
    function exitMain(){
        setOpen(false);
    };

    //保存入库单
    async function saveMain(){
         const fdata2=formRef_main.current?.getFieldsValue();
        //  alert(JSON.stringify(fdata2));   
        //表头数据
         const fdata={vendor_id:fdata2.vendor_id,
                      warehouse_id:fdata2.warehouse_id,
                      stockin_time:moment(moment(fdata2.stockin_time).toDate()).format('YYYY-MM-DD HH:mm:ss'),
                      memo:fdata2.memo,
                      id:fdata2.id,
                      intype_id:fdata2.intype_id,
                      source_type:fdata2.source_type,
         };
         //表体数据
        //   alert(JSON.stringify(fdata2.editable_main));
         const tdata=fdata2.editable_main.map((item:any)=>({
               material_id:item.material_id,
               userdefine_id:item.userdefine_id,
               userdefine_name:item.userdefine_name,
               quantity:item.quantity,
               source_type:item.source_type,
               source_order_mid:item.source_order_mid,
               source_order_did:item.source_order_did,
               id:item.id,
               mid:item.mid,
           }));
        //  alert(JSON.stringify(tdata));
        // x_id,operater_id,etype,source,tdata
        const x=await s_stockIn({x_id:1,operater_id:initialState?.currentUser?.userid,etype,
                                 source:'stock_in_purchase',tdata:{fdata,tdata}});
        if(x.success){
            message.success('保存成功');
            setEtype(0);
            actionRef_m.current?.reloadAndRest?.();
            //修改当前的表单界面值
            formRef_main.current?.setFieldsValue({
                vouch_code:x.data[0][0].vouch_code,
                id:x.data[0][0].id,
                editable_main:x.data[1],
            });
        }else
          message.warning('保存失败，请联系管理员');
    };

    //打开查询窗口
    async function doQuery(){
    //    根据参数查找数据，返回结果并赋值
       const vouch_code=formRef_main.current?.getFieldValue('query_vouch_code');
       const material_id=formRef_main.current?.getFieldValue('query_material_id');
       const vendor_id=formRef_main.current?.getFieldValue('vendor_id');

       var operate_time=formRef_main.current?.getFieldValue('query_operate_time');
       if(operate_time!=undefined&&operate_time.length>0){
            operate_time=[
                        moment(moment(operate_time[0]).toDate()).format('YYYY-MM-DD HH:mm:ss'),
                        moment(moment(operate_time[1]).toDate()).format('YYYY-MM-DD HH:mm:ss')
                         ];
       }
       
       setTdata3([]);
       const x=await s_getStockInfo({source:'v_purchase_order_for_stockin',x_id:1,fdata:{vouch_code,material_id,vendor_id,operate_time}});
       if(x.data[0]&&x.data[0].length>0){
            
            // alert(JSON.stringify(x.data[0]));
            //  formRef_query.current?.setFieldValue('editable_query',x.data[0]);
            //  formRef_query.current?.setFieldValue('ft',111);
             setTdata3(x.data[0]);
             setOpenQuery(true);
            //  formRef_query.current?.setFieldValue('ff',x.data[0][0].rid);
            //  alert(x.data[0][0].rid);
            // showQuery();
       }else
         message.warning('没有找到对应的采购单');
       
    };

    //退出查询窗口
    async function exitQuery(){
        setOpenQuery(false);
    }

    //编辑实际入库数
    function editQuery(){
       var fdata=formRef_query.current?.getFieldValue('editable_query');
       fdata.map((item:any)=>{
          actionRef_query.current?.startEditable(item.rid);
       });
    };
    //将选中的采购数据，加入到入库单中
    function addQuery2Order(){
        //  alert(JSON.stringify(selectedRecords3));
        var record=selectedRecords3.map((item:any)=>{
            return {
                 ...item,
                quantity:item.quantity_in_now,
                source_order_did:item.did,
                source_order_mid:item.id,
                source_type:1,
                memo:null,
            };
        });

        var fdata=formRef_main.current?.getFieldValue('editable_main');
        fdata=fdata?fdata:[];
        
        //   alert(JSON.stringify(fdata));
        record=record.concat(fdata);
        formRef_main.current?.setFieldValue('editable_main',record);
        //  alert(JSON.stringify(record));
    }

//   ===================================================================================================
    return <>
         <ProCard title='外发入库单列表' style={{height:450,overflow:'auto'}}
             extra={<Space>
                <Button>查询</Button>
                {/* <Button onClick={()=>openMain(1)}>新增</Button>
                <Button onClick={()=>openMain(0)}>编辑</Button> */}
                <Button onClick={()=>operateInfo(5)}>审核</Button>
                <Button onClick={()=>operateInfo(6)}>取消审核</Button>
                <Button onClick={()=>operateInfo(2)}>关闭</Button>
                <Button onClick={()=>operateInfo(3)}>删除</Button>
                <Button onClick={()=>operateInfo(1)}>恢复</Button>
             </Space>}
         >
              <ProTable<DataType>
                  actionRef={actionRef_m}
                  search={{span:4}}
                  options={false}
                  columns={columns}
                  rowKey='id'
                  request={async (param)=>{
                    const x=await s_getStockInfo({source:'v_stock_in_produce_main',x_id:1,
                                   fdata:{id:0,source_type:3,param}});
                    setTotal(x.data[0][0].count);               
                    return{
                        data:x.data[1],
                        success:true,
                    }
                  }}
                  rowSelection={{
                    type:'radio',
                    selectedRowKeys:selectedLineKeys,
                    async  onChange(selectedRowKeys, selectedRows, info) {
                        setSelectedRecords(selectedRows);
                        setSelectedLineKeys(selectedRowKeys);
                        //刷新子表明细
                        const x=await s_getStockInfo({source:'v_stock_in_produce_detail',x_id:1,
                                   fdata:{mid:selectedRowKeys.length>0?selectedRowKeys[0]:0}});
                        setTdata(x.data[0])
                    },
                  }}
        onRow={(record)=>{
            return {
              onClick:async ()=>{
                        const k=record.id;setSelectedRecords([record]);
                        setSelectedLineKeys([k]);
                        //刷新子表明细
                        const x=await s_getStockInfo({source:'v_stock_in_produce_detail',x_id:1,
                                   fdata:{mid:k?k:0}});
                        setTdata(x.data[0])
              },
            }
           }}
                  pagination={{
                    showQuickJumper:true,
                    showSizeChanger:true,
                    defaultPageSize:5,
                    defaultCurrent:1,
                    total,
                  }}
                />
         </ProCard>
         {/* 入库单明细表---------- */}
         <ProCard style={{height:300,overflow:'auto'}}>
         <ProTable<DataType2>
                  search={false}
                  options={false}
                  columns={columns2}
                  rowKey='id'
                  dataSource={tdata}
                />
        </ProCard>

        {/* 入库单的新增/编辑主界面---------------------------------------------------------------- */}
        <Modal open={open} width='90%' style={{top:10}} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
               closable destroyOnClose onCancel={()=>exitMain()} onClose={()=>exitMain()}>
           <ProCard title={etype==1?'新增采购入库':'编辑采购入库'} style={{height:900,overflow:'auto'}}
                extra={<Space>
                    <Button onClick={()=>formRef_main.current?.submit()}>保存采购单</Button>
                    <Button onClick={()=>exitMain()}>退出</Button>
                </Space>}>
                <ProForm formRef={formRef_main} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:6}}
                    labelWrap submitter={false} onFinish={()=>saveMain()}
                    initialValues={etype==0?{
                                  ...selectedRecords[0],
                                  editable_main:tdata,
                               }
                             :{stockin_time:moment(),source_type:1}}
                    >
                      <Row gutter={8}>
                         <Col span={6}>
                           <Space.Compact>
                                <Button  style={{fontSize:30,height:50}} >采购单码</Button>
                                <ProFormText name='query_vouch_code'  width={300}
                                   fieldProps={{
                                      style:{fontSize:30,color:'red',height:50}
                                   }}
                                />
                           </Space.Compact>
                         </Col>
                         <Col span={6}>
                           <Space.Compact>
                                <Button  style={{fontSize:30,height:50}} >SKU码</Button>
                                <ProFormText name='query_material_id'  width={300}
                                   fieldProps={{
                                      style:{fontSize:30,color:'red',height:50}
                                   }}
                                />
                           </Space.Compact>
                         </Col>
                         <Col span={6}>
                           <Space.Compact>
                                <Button  style={{fontSize:30,height:50}} >下单日期</Button>
                                <ProFormDateRangePicker name='query_operate_time'  width={300}
                                   fieldProps={{
                                      style:{fontSize:30,color:'red',height:50}
                                   }}
                                />
                           </Space.Compact>
                         </Col>
                         <Col span={5}>
                         <Button  style={{fontSize:30,height:50,marginLeft:50}}
                            onClick={()=>doQuery()}
                         >查询</Button>
                         </Col>
                      </Row>  
                      {/* <Divider/>   */}
                     <Row gutter={8}>
                         <Col span={4}>
                           {/* <ProFormText name='id' label='id'/> */}
                            <ProFormText name='vouch_code' label='入库单号' width={200} />
                         </Col>
                         <Col span={4}>
                            <ProFormSelect name='vendor_id' label='供应商' width={200} 
                               rules={[{required:true,message:'必填项'}]}
                               showSearch
                               request={async ()=>{
                                     const x=await s_getSelectData({x_id:1,source:'v_vendor'});
                                     return x.data;}}
                            />
                         </Col>
                         <Col span={4}>
                           <ProFormSelect name='warehouse_id' label='仓库' width={200} 
                           rules={[{required:true,message:'必填项'}]}
                               showSearch
                               request={async ()=>{
                                    const x=await s_getSelectData({x_id:1,source:'base2_ware'});
                                      return x.data;}}
                                />
                         </Col>
                         <Col span={4}>
                            
                            <ProFormDatePicker name='stockin_time' label='日期' width={200} />
                         </Col>
                          <Col span={3}>
                            
                            <ProFormRadio.Group name='source_type' label='日期' width={200} 
                               options={[{value:1,label:'蓝字'},{value:-1,label:'红字',style:{color:'red'}}]}
                            />
                         </Col>
                         
                     </Row>   
                     <Row gutter={8}>
                     <Col span={4}>
                            {/* <ProFormText name='intype_id' label='XXX'/> */}
                            <ProFormSelect name='intype_id' label='入库类型' width={200} 
                        //    rules={[{required:true,message:'必填项'}]}
                               showSearch
                               request={async ()=>{
                                    const x=await s_getSelectData({x_id:1,source:'base_intype'});
                                      return x.data;}}
                                />
                             
                         </Col>
                         <Col span={4}>
                            <ProFormText name='memo' label='备注' width={500}/>
                         </Col>
                     </Row>
                     

                     <EditableProTable<DataType2>
                        name='editable_main'
                        rowKey='rid'
                        columns={columns2}
                        actionRef={actionRef_main}
                        editableFormRef={editableRef_main}
                        editable={{
                            type:'multiple',
                        }}
                        recordCreatorProps={false}
                        search={false}
                        options={false}
                        />
                </ProForm>
           </ProCard>
        </Modal>
        {/* 采购单的查询界面---在扫码时调出------------------------------------- */}
        <Modal open={openQuery} width='90%' style={{top:10}} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
               closable destroyOnClose onCancel={()=>exitQuery()} onClose={()=>exitQuery()}>
           <ProCard title= '查询采购单'  style={{height:900,overflow:'auto'}}
                extra={<Space>
                    <Button onClick={()=>editQuery()}>编辑本次入库数</Button>
                    <Button onClick={()=>addQuery2Order()}>添加到入库单</Button>
                    <Button onClick={()=>exitQuery()}>退出</Button>
                </Space>}>
                <ProForm formRef={formRef_query} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:6}}
                    labelWrap submitter={false}
                    initialValues={{editable_query:tdata3}}
                    >
                    <EditableProTable<DataType3>
                        name='editable_query'
                        actionRef={actionRef_query}
                        editableFormRef={editableRef_query}
                        rowKey='rid'
                        options={false}
                        columns={columns3}
                        // dataSource={tdata3}
                        rowSelection={{
                            type:'checkbox',
                            async onChange(selectedRowKeys, selectedRows, info) {
                                 setSelectedRecords3(selectedRows);
                            },
                        }}
                        recordCreatorProps={false}
                        pagination={{
                            pageSize:10,
                        }}
                        editable={{
                            type:'multiple',
                        }}
                        scroll={{y:600}}
                    /> 
                    {/* {JSON.stringify(tdata3)} */}
                    {/* <ProFormText name='ft' label='测试' /> */}
                </ProForm>
           </ProCard>
        </Modal>
        </> ;
}

export default App;